package com.issuser.appdeducations_2.activity

import android.content.Context
import android.graphics.PixelFormat
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.Toast
import com.google.gson.Gson
import com.issuser.appdeducations_2.App
import com.issuser.appdeducations_2.R
import com.issuser.appdeducations_2.mina.FirstClientHandler
import kotlinx.android.synthetic.main.activity_main.*
import java.net.URLEncoder

class Main : AppCompatActivity() {
    lateinit var app: App
    lateinit var gson: Gson
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        app = application as App
        gson = Gson()
    }

    fun dian(v: View) {
        when (v.id) {
            R.id.sendBt -> {
                var content = contentEdit.text.toString()
                sendMSG(content)
            }
            R.id.pc_next -> {
                var msgbean = MsgBean()
                msgbean.type = 1
                msgbean.devicesID = FirstClientHandler.deviceID
                sendMSG(gson.toJson(msgbean))
            }
        }
    }

    fun sendMSG(str: String) {
        app.sendMssageToServer(URLEncoder.encode(str, "utf-8"))
        Toast.makeText(applicationContext, "$str", Toast.LENGTH_SHORT).show();
    }

    override fun onStop() {
        super.onStop()
        val button = Button(applicationContext)
        val wm = applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val wmParams = WindowManager.LayoutParams()

        /**
         * 以下都是WindowManager.LayoutParams的相关属性 具体用途请参考SDK文档
         */
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE // 这里是关键，你也可以试试2003
        wmParams.format = PixelFormat.RGBA_8888 // 设置图片格式，效果为背景透明

        /**
         * 这里的flags也很关键 代码实际是wmParams.flags |=FLAG_NOT_FOCUSABLE;
         * 40的由来是wmParams的默认属性（32）+ FLAG_NOT_FOCUSABLE（8）
         */
        wmParams.flags = (WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
        wmParams.width = 1
        wmParams.height = 1
        wm.addView(button, wmParams) // 创建View
    }
}
